﻿$(function () {
  if (typeof epgOpenModal === "undefined") {
    var scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.src = '/Resource/Video/epgModal.js';
    $("head").append(scriptTag);
    $("head").append("<link type='text/css' rel='stylesheet' href='/Resource/Video/epgModal.css' />");
  }

  var allVideos = [];

  var videoObj = function (target, type, autoPlay) {
    this.type = type;
    switch (this.type) {
      case 'mp4':
        this.type = 'video/mp4';
        break;
      case 'webm':
        this.type = 'video/webm';
        break;
      case 'ogg':
      case 'ogv':
        this.type = 'video/ogg'
        break;
      default:
        break;
    }
    if (autoPlay !== false) {
      this.autoPlay = ' autoplay';
    } else {
      this.autoPlay = '';
    }
    this.poster = '';
    this.captions = [];
    this.src = target.attr('href');

    if (this.type === 'YouTube') {
      //Turn YouTube 'watch' URL into 'embed' URL
      var watchIdx = this.src.indexOf('watch');
      if (watchIdx >= 0) {
        var params = this.src.split('?')[1].split('&');
        for (var i = 0; i < params.length; i++) {
          var thisParam = params[i].split('=');
          if ((thisParam[0] === 'v') && (thisParam[1] !== null)) {
            this.src = '//www.youtube.com/embed/' + thisParam[1];
          }
        }
      }
    } else {
      var thisVidObg = this;
      target.children('input.popuPoster').each(function () {
        thisVidObg.poster = $(this).data('imgsrc');
      });
      target.children('input.popuCaption').each(function () {
        var caption = $(this);
        thisVidObg.captions.push({ src: caption.data('src'), lang: caption.data('lang'), langAbbr: caption.data('langabbr') });
      });
    };
  }

  $.fn.popuVideoModalWindow = function (/*autoplay boolean*/) {
    var target = $(this);
    var args = arguments;
    target.each(function () {
      var targetInstance = $(this);
      if (targetInstance.is("a")) {
        var autoPlay = true;
        if (args.length > 0) {
          for (var i = 0; i < args.length; i++) {
            if (typeof args[i] === "boolean") {
              autoPlay = args[i];
            }
          }
        }
        var href = targetInstance.attr('href');
        if (href.indexOf('youtu') !== -1) {
          allVideos.push(new videoObj(targetInstance, 'YouTube', autoPlay));
          targetInstance.attr('href', '#').on('click', epgPopupVideo).data('vidNum', (allVideos.length - 1));
        } else {
          var extensionIdx = href.lastIndexOf('.') + 1;
          var extension = href.substr(extensionIdx, href.length);
          if ((extension === 'mp4') || (extension === 'ogv') || (extension === 'ogg') || (extension === 'webm') || (extension === 'wmv') || (extension === 'wmx') || (extension === 'ism')) {
            allVideos.push(new videoObj(targetInstance, extension, autoPlay));
            targetInstance.attr('href', '#').on('click', epgPopupVideo).data('vidNum', (allVideos.length - 1));
          }
        }
      } else { }
    });
  };

  var epgPopupVideo = function (event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
    target = (event.currentTarget) ? event.currentTarget : event.srcElement;
    videoInstance = allVideos[$(target).data('vidNum')];
    if ($(window).width() <= 600) {
      var win = window.open(videoInstance.src, '_blank');
      win.focus();
    } else {
      if (videoInstance.type === 'YouTube') {
        var htmlString = "<div id='epgPopupYoutubeCont' style='width:100%; height:auto; max-width:800px; max-height:100%; position:relative;'>" +
            "<div class='epgPopupYTHeight' style='width:100%; padding-bottom:56.25%;'>" +
              "<iframe src='" + videoInstance.src + "' style='position:absolute; height:100%; width:100%; top:0px; left:0px;' frameborder='0' allowfullscreen></iframe>" +
            "</div>" +
          "</div>";
      } else {
        var htmlString = "<div style='width:100%; height:auto; max-width:800px; max-height:100%; position:relative; overflow:hidden; text-align:left;'>" +
          "<div style='padding-bottom:56.25%; position:relative;'>" +
          "<div style='width:100%; height:100%; text-align:left; position:absolute; background-color:#000000;'>" +
          "</div>" +
          "</div>" +
          "<video id='epgPopupVideo' style='width:100%; height:100%; background-color:#000; position:absolute; top:0px; left:0px;' controls" + videoInstance.autoPlay + " poster='" + videoInstance.poster + "'>" +
  	      "<source src='" + videoInstance.src + "' ";
        if ((videoInstance.type === 'video/mp4') || (videoInstance.type === 'video/webm') || (videoInstance.type === 'video/ogg')) {
          htmlString += "type='" + videoInstance.type + "' "
        }
        htmlString += "/>";

        for (var i = 0; i < videoInstance.captions.length; i++) {
          htmlString += "<track src='" + videoInstance.captions[i].src + "' kind='subtitles' srclang='" + videoInstance.captions[i].langAbbr + "' label='" + videoInstance.captions[i].lang + "' />";
        }

        var silverlightAutoplay = videoInstance.autoPlay;
        if (videoInstance.autoPlay === " autoplay") {
          silverlightAutoplay = true;
        }

        htmlString += "<object class='pf-silverlight' style='width:100%; height:100%;' data='data:application/x-silverlight-2,' type='application/x-silverlight-2' data-poster='" + videoInstance.poster + "'>" +
  		    "<param name='source' value='/global/enterprise/RichMedia/smooth/SmoothStreamingPlayer.xap'/>" +
  		    "<param name='minRuntimeVersion' value='4.0.50826.0' />" +
  		    "<param name='autoUpgrade' value='true' />" +
  		    "<param name='enableGPUAcceleration' value='true' />" +
  		    "<param name='windowless' value='true' />" +
          "<param name='allowfullscreen' value='true' />" +
  		    "<param name='InitParams' value='scriptablename=Player,autoplay=" + silverlightAutoplay;

        var ismIdx = videoInstance.src.lastIndexOf('.ism');
        if (ismIdx > 0) {
          //Make sure '/manifest' is at the end of the URL for .ism files, otherwise add it
          var manifestIdx = videoInstance.src.indexOf('/manifest');
          if ((manifestIdx > 0) && (manifestIdx + 9 === videoInstance.src.length)) {
            htmlString += ", mediaurl=" + videoInstance.src;
          } else if (ismIdx + 4 === videoInstance.src.length) {
            htmlString += ", mediaurl=" + videoInstance.src + "/manifest";
          } else {
            console.log('Video extension error');
          }
        } else {
          htmlString += ", deliverymethod=Progressive Download, mediaurl=" + videoInstance.src;
        }
        htmlString += "' />";

        /* Place Flash fallback here */

        htmlString += "</object>" +
            "</video>" +
          "</div>";
      }
      epgOpenModal(htmlString);
    }
  };
});